package com.fs.uc.base.repo;

import com.fs.uc.base.domain.Person;
import com.fs.uc.base.exception.NotFoundException;
import com.fs.uc.base.exception.ParamException;
import io.quarkus.hibernate.orm.panache.PanacheRepository;

import javax.enterprise.context.ApplicationScoped;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 崔超
 * 2021/12/7
 */
@ApplicationScoped
public class PersonRepository implements PanacheRepository<Person> {
    static final String OPENID_FIELD = "openid";
    static final String PHONE_FIELD = "phone";
    static final String CURRENT_ORG_FIELD = "currentOrg_id";

    public Person getById(Long personId) {
        Person person = findById(personId);
        if (person == null) {
            throw new NotFoundException();
        }
        return person;
    }

    public Person getByOpenId(String openId) {
        return find(OPENID_FIELD, openId).singleResult();
    }

    public Person getByPhone(String phone) {
        return find(PHONE_FIELD, phone).singleResult();
    }

    public Person findByPhone(String phone) {
        return find(PHONE_FIELD, phone).firstResult();
    }

    public Person findByOpenId(String openId) {
        return find(OPENID_FIELD, openId).firstResult();
    }

    public List<Person> findByIds(List<Long> ids) {
        Map<String, Object> params = new HashMap<>();
        params.put("list", ids);
        return list("select p from Person p where id in (:list)", params);
    }

    public List<Person> findByCurrentOrg(Long orgId) {
        return list(CURRENT_ORG_FIELD, orgId);
    }

    public List<Person> findByCurrentOrgs(List<Long> orgIds) {
        Map<String, Object> params = new HashMap<>();
        params.put("list", orgIds);
        return list("select p from Person p where currentOrg_id in (:list)", params);
    }

    public void update(Person person) {
        if (person.id == null) {
            throw new ParamException();
        }
        getEntityManager().merge(person);
        persist(person);
    }
}
